<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <FullScreen
        v-model="showDialog"
        title="资产效益分析详情"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
        </template>
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation
              :info="infoList"
              :labelWidth="infoList.labelWidth"
            >
            </BasicInformation>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('detailInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <PageFilter
              :filter-list="filterInfo.list"
              v-model:query="filterInfo.query"
            >
              <template v-slot:filter-year>
                <el-date-picker
                  v-model="year"
                  type="year"
                  :clearable="false"
                  format="YYYY"
                  value-format="YYYY"
                  :disabled-date="datePickerOptions.disabledDate"
                  @change="getList"
                >
                </el-date-picker>
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <PageTable
                v-model:data="tableInfo.data"
                :pager="false"
                :checkBox="false"
                :tab-index="true"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
              >
              </PageTable>
            </div>
            <div class="layui-row" style="margin-top: 30px">
              <div class="layui-col-md12">
                <div v-for="(item, index) in echartsList" :key="index">
                  <div :id="item.id" style="height: 300px"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </FullScreen>
    </div>

    <Modify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :orderId="modifyInfo.orderId"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="assetAnalysisDetail">
import Modify from './modify'
import { getAssetAnalysisById } from '@/api/asset.js'
import * as echarts from 'echarts'
import moment from 'moment'
import { getAssetMonthIncomeCostQuery } from '@/api/dataQuery.js'

const { proxy } = getCurrentInstance()
const props = defineProps(['visible', 'id'])
const year = ref(moment(new Date()).format('YYYY'))
const datePickerOptions = ref({
  disabledDate(time) {
    // 大于当前的时间都不能选 (+十分钟让点击此刻的时候可以选择到当前时间)
    return time.getTime() > +new Date() + 1000 * 600 * 1
  },
})
const echartsList = ref([
  {
    title: '月收入支出对比',
    id: 'monthlyIncomeExpenditure',
  },
  {
    id: 'person',
  },
  {
    id: 'income',
  },
  {
    id: 'monthlyIncome',
  },
  {
    id: 'actualUsageRate',
  },
])
const modifyInfo = ref({
  visible: false,
  title: '',
  orderId: '',
})
const infoList = ref({
  data: {},
  fieldList: [
    {
      label: '资产名称',
      value: 'assetName',
      type: 'text',
    },
    {
      label: '资产卡片号',
      value: 'assetCode',
      type: 'text',
    },

    {
      label: '规格',
      value: 'standard',
      type: 'text',
    },
    { label: '厂家', value: 'brandName', type: 'text' },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'text',
    },
    {
      label: '仓库',
      value: 'depotName',
      type: 'text',
    },
    {
      label: '使用部门',
      value: 'useDeptName',
      type: 'text',
    },
    {
      label: '管理部门',
      value: 'manageDeptName',
      type: 'text',
    },
    { label: '位置', value: 'location', type: 'text' },
    {
      label: '设备购入金额(元)',
      value: 'primitiveOriginalAmount',
      type: 'text',
    },
  ],
  labelWidth: '135px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  list: [
    {
      label: '报表年度',
      value: 'year',
      type: 'slot',
      event: getList,
    },
  ],
})
// 表格相关
const tableInfo = ref({
  api: null,
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
  fieldList1: [
    {
      label: '月份',
      value: 'month',
    },
    { label: '本月预计收入(元)', value: 'estimateTreatIncome' },
    { label: '本月实际收入(元)', value: 'incomeAmount' },
    { label: '预计检查(治疗)人次/月', value: 'estimateTreatPersonTime' },
    { label: '实际检查(治疗)人次/月', value: 'treatPersonTime' },
    {
      label: '阳性人次',
      value: 'positivePersonTime',
    },
    { label: '预计开机时长/月', value: 'estimatePowerUp' },
    {
      label: '实际开机时长(h)',
      value: 'powerUpTime',
    },
    {
      label: '本月支出(元)',
      value: 'allCostProject',
    },
  ],
  fieldList2: [
    {
      label: '净利润(元)',
      value: 'netAmount',
    },
    {
      label: '月收益率(%)',
      value: 'incomeRate',
    },
    {
      label: '月利润率(%)',
      value: 'profitRate',
    },
    {
      label: '阳性率(%)',
      value: 'positiveRate',
    },
    {
      label: '实际使用率(%)',
      value: 'useRate',
    },
    {
      label: '投资回报期(月)',
      value: 'investPayBackPeriod',
    },
  ],
})
const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})
const canUpdate = computed(() => {
  return proxy.$permission('assetAnalysis:update')
})
function returnModify() {
  getMain()
}
function returnBack() {
  proxy.$emit('returnBack', false)
}
//更新
function update() {
  modifyInfo.value.title = '修改效益分析资产'
  modifyInfo.value.orderId = infoList.value.data.id
  modifyInfo.value.visible = true
}

function getList() {
  if (year.value) {
    if (year.vlaue === moment(new Date()).format('YYYY')) {
      //今年
      let _year = moment(new Date()).format('YYYY')
      let month = moment(new Date()).format('YYYY-MM').split('-')[1]
      if (month === '12') {
        filterInfo.value.query.businessDateGreater =
          String(Number(_year) - 1) + '-01-01'
      } else {
        filterInfo.value.query.businessDateGreater =
          String(Number(_year) - 1) + '-' + String(Number(month) + 1) + '-01'
      }
      filterInfo.value.query.businessDateLess =
        moment(new Date()).format('YYYY-MM') + '-31'
    } else {
      //以往年份
      filterInfo.value.query.businessDateGreater = year.value + '-01-01'
      filterInfo.value.query.businessDateLess = year.value + '-12-31'
    }
  } else {
    year.value = moment(new Date()).format('YYYY')
    getList()
    return
  }
  filterInfo.value.query.assetIdMult = infoList.value.data.assetId
  filterInfo.value.query.reportData = true
  getAssetMonthIncomeCostQuery(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      if (res.data && res.data.list) {
        let data = res.data.list || []
        tableInfo.value.data = data.map((item) => {
          return {
            ...item,
            ...item.costMap,
          }
        })
        echartsList.value = [
          {
            title: '月收入支出对比',
            id: 'monthlyIncomeExpenditure',
          },
          {
            id: 'person',
          },
          {
            id: 'income',
          },
          {
            id: 'monthlyIncome',
          },
          {
            id: 'actualUsageRate',
          },
        ]
        proxy.$nextTick(() => {
          getEchart(res.data)
        })
      } else {
        tableInfo.value.data = []
        echartsList.value = []
      }
    }
  })
}
function getEchart(data) {
  if (data) {
    //月收入支出对比
    let echart1 = echarts.init(
      document.getElementById('monthlyIncomeExpenditure')
    )
    let option1 = {
      title: {
        text: '月收入支出对比',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
      },
      legend: {
        data: ['本月收入', '本月支出', '本月利润'],
      },
      xAxis: {
        data: data.incomeCostCompareData.xDate || [],
      },
      yAxis: {},
      series: [
        {
          name: '本月收入',
          type: 'bar',
          data: data.incomeCostCompareData.incomeYdate || [],
        },
        {
          name: '本月支出',
          type: 'bar',
          data: data.incomeCostCompareData.costYdata || [],
        },
        {
          name: '本月利润',
          type: 'bar',
          data: data.incomeCostCompareData.netYdata || [],
        },
      ],
    }
    if (data) {
      echart1.setOption(option1)
    }

    //预计人次与实际人次对比
    let echart2 = echarts.init(document.getElementById('person'))
    let option2 = {
      title: {
        text: '预计人次与实际人次对比',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
      },
      legend: {
        data: ['预计检查人次', '实际检查人次'],
      },
      xAxis: {
        data: data.treatPersontimeCompareData.xDate || [],
      },
      yAxis: {},
      series: [
        {
          name: '预计检查人次',
          type: 'line',
          data:
            data.treatPersontimeCompareData.estimateTreatPersonTimeYdata || [],
        },
        {
          name: '实际检查人次',
          type: 'line',
          data: data.treatPersontimeCompareData.treatPersonTimeYdata || [],
        },
      ],
    }
    echart2.setOption(option2)
    //预计收益与实际收益对比
    let echart3 = echarts.init(document.getElementById('income'))
    let option3 = {
      title: {
        text: '预计收益与实际收益对比',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
      },
      legend: {
        data: ['本月预计收入', '本月实际收入'],
      },
      xAxis: {
        data: data.incomeCompareData.xDate || [],
      },
      yAxis: {},
      series: [
        {
          name: '本月预计收入',
          type: 'bar',
          data: data.incomeCompareData.estimateTreatIncomeYdata || [],
        },
        {
          name: '本月实际收入',
          type: 'bar',
          data: data.incomeCompareData.incomeYdata || [],
        },
      ],
    }
    echart3.setOption(option3)
    //月收益分析
    let echart4 = echarts.init(document.getElementById('monthlyIncome'))
    let option4 = {
      title: {
        text: '月收益分析',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
      },
      legend: {
        data: ['月收益率', '月利润率'],
      },
      xAxis: {
        data: data.monthIncomeAnalysisData.xDate || [],
      },
      yAxis: {},
      series: [
        {
          name: '月收益率',
          type: 'line',
          smooth: true,
          data: data.monthIncomeAnalysisData.incomeRateYdate || [],
        },
        {
          name: '月利润率',
          type: 'line',
          smooth: true,
          data: data.monthIncomeAnalysisData.profitRateYdata || [],
        },
      ],
    }
    echart4.setOption(option4)
    //实际使用率
    let echart5 = echarts.init(document.getElementById('actualUsageRate'))
    let option5 = {
      title: {
        text: '实际使用率',
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
      },
      xAxis: {
        data: data.useRateData.xDate || [],
      },
      yAxis: {},
      series: [
        {
          type: 'line',
          data: data.useRateData.useRateYdate || [],
        },
      ],
    }
    echart5.setOption(option5)
  }
}
function getMain() {
  getAssetAnalysisById(props.id).then((res) => {
    if (res && res.success) {
      infoList.value.data = res.data
      getList()
    }
  })
}
function getCostFieldList() {
  //获取支出项目字段
  tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
    tableInfo.value.fieldList2
  )
  let asset_cost_project =
    proxy.$store.state.permission.dict['asset_cost_project']
  if (asset_cost_project && asset_cost_project.length) {
    let fieldList = asset_cost_project.map((item) => {
      let obj = {
        label: item.name + '(元)',
        value: item.code,
      }
      return obj
    })
    tableInfo.value.fieldList = tableInfo.value.fieldList1.concat(
      fieldList,
      tableInfo.value.fieldList2
    )
  }
}
onMounted(() => {
  getCostFieldList()
  if (props.id) {
    getMain()
  }
})
</script>
<style scoped lang="scss">
:deep(.table-scroll-hidden) > .el-table {
  overflow-y: hidden;
}
:deep(.el-dialog__body) {
  height: 355px;
  display: flex;
  flex-direction: column;
}
</style>
